<template>
  <el-card style="margin: 20px;">
    <h2>用户管理界面</h2>

    <!-- 用户表格 -->
    <!-- <el-table :data="currentPageData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60"></el-table-column>
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="age" label="年龄" width="80"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="220"></el-table-column>
      <el-table-column prop="phone" label="电话" width="150"></el-table-column>
    </el-table> -->
     <!-- 工具栏 -->
    <div style="margin-bottom: 20px; display: flex; gap: 10px; align-items: center;">
      <el-input v-model="searchId" placeholder="请输入用户ID" style="width: 200px;" />
      <el-button @click="fetchUserById">查询</el-button>
      <el-button type="primary" @click="openAddDialog">新增用户</el-button>
    </div>

    <!-- 用户表格 -->
    <el-table :data="currentPageData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60"></el-table-column>
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="age" label="年龄" width="80"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="220"></el-table-column>
      <el-table-column prop="phone" label="电话" width="150"></el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
      layout="prev, pager, next"
      :total="users.length"
      v-model:page="currentPage"
      :page-size="pageSize"
      @current-change="handlePageChange"
      style="margin-top: 20px"
    />

    <!-- 新增/编辑用户对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '新增用户'" width="40%">
      <el-form :model="form" label-width="100px" ref="formRef">
        <el-form-item label="姓名">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="form.age" :min="1" :max="150" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">{{ isEdit ? '更新' : '保存' }}</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import userApi from '@/api/userApi'
import { ElMessage,ElMessageBox } from 'element-plus'


// 响应式变量
const users = ref([])
const currentPage = ref(1)
const pageSize = ref(5) // 每页显示数量

//数据定义
const searchId = ref('')
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = ref({
  id: null,
  name: '',
  age: 0,
  email: '',
  phone: ''
})
const formRef = ref(null)

const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return users.value.slice(start, start + pageSize.value)
})

onMounted(async () => {
  //  try {
    const res = await userApi.getUsers()
   if (res.code === null || res.code === 200) {
      // 注意：data 是字符串，要手动 parse
      users.value = JSON.parse(res.data)
      console.log(users.value);
    } else {
      // console.error('接口返回错误:', result.msg)
    }
    
})
// 获取数据
async function fetchData() {
  try {
    // const response = await axios.get('http://localhost:3000/users') // 替换为你的接口地址
    const response =  await userApi.getUsers()
    const result = response.data

    if (result.code === null || result.code === 200) {
      // 注意：data 是字符串，要手动 parse
      users.value = JSON.parse(result.data)
    } else {
      console.error('接口返回错误:', result.msg)
    }
  } catch (err) {
    console.error('请求失败:', err)
  }
}

// 根据 ID 查询用户
// async function fetchUserById() {
//   if (!searchId.value) {
//     ElMessage.warning('请输入用户ID')
//     return
//   }

//   try {
//     const response = await axios.get(`http://localhost:3000/users/${searchId.value}`) // 替换为你的接口地址
//     const result = response.data
//     if (result.code === null || result.code === 200) {
//       users.value = [JSON.parse(result.data)]
//       currentPage.value = 1
//     } else {
//       ElMessage.error(result.msg || '未找到该用户')
//     }
//   } catch (err) {
//     ElMessage.error('请求失败，请检查网络或ID是否正确')
//     console.error('请求失败:', err)
//   }
// }

// 打开新增对话框
function openAddDialog() {
  isEdit.value = false
  form.value = { name: '', age: 0, email: '', phone: '' }
  dialogVisible.value = true
}

// 打开编辑对话框
function openEditDialog(user) {
  isEdit.value = true
  form.value = { ...user }
  dialogVisible.value = true
}

// 提交新增或编辑
async function submitForm() {
  try {
    if (isEdit.value) {
      // 编辑用户
      await userApi.updateUser(form.value.id, form.value)
      ElMessage.success('用户信息已更新')
    } else {
      // 新增用户
      const res =userApi.saveUser(form.value)
      users.value.push(res.data)
      ElMessage.success('用户已新增')
    }

    dialogVisible.value = false
    fetchData()
  } catch (err) {
    ElMessage.error('操作失败，请重试')
    console.error(err)
  }
}

// 删除用户
async function deleteUser(id) {
// 弹出确认框
    await ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

  try {
    userApi.delectUserById(id)
    ElMessage.success('用户已删除')
  } catch (err) {
    ElMessage.error('删除失败')
    console.error(err)
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>